package com.homelink.android.smstohtml.convert;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;

import com.homelink.android.smstohtml.model.Sms;

public class ConvertThread extends AsyncTask<String, Integer, String> {
	private Context context;

	/**
	 * phone number as key, and SMS list as entry
	 */
	private HashMap<String, ArrayList<Sms>> smsMap;

	public ConvertThread(Context ctx) {
		context = ctx;
	}

	@Override
	protected String doInBackground(String... params) {
		if (smsMap == null) {
			smsMap = new HashMap<String, ArrayList<Sms>>();
		} else {
			smsMap.clear();
		}
		readSmsFromCur();
		writeToSD();
		Log.d("SmsToHtmlActivty", "doInBackground");

		return null;
	}

	private Cursor readSms() {
		Uri uri = Uri.parse("content://sms/");
		String[] projection = new String[] { Sms.Field.ID, Sms.Field.address,
				Sms.Field.person, Sms.Field.body, Sms.Field.date,
				Sms.Field.type };
		Cursor cur = context.getContentResolver().query(uri, projection, null,
				null, "date desc");
		return cur;
	}

	private void readSmsFromCur() {
		Cursor cur = readSms();
		if (cur.moveToFirst()) {
			do {
				Sms sms = new Sms();
				sms.id = cur.getString(cur.getColumnIndex(Sms.Field.ID));
				sms.address = cur.getString(cur
						.getColumnIndex(Sms.Field.address));
				sms.person = cur
						.getString(cur.getColumnIndex(Sms.Field.person));
				sms.body = cur.getString(cur.getColumnIndex(Sms.Field.body));
				sms.date = cur.getString(cur.getColumnIndex(Sms.Field.date));
				sms.type = cur.getString(cur.getColumnIndex(Sms.Field.type));
				String phone = sms.address;
				if (phone.length() >= 11) {
					phone = phone.substring(phone.length() - 11);
				}
				ArrayList<Sms> smsList = smsMap.get(phone);
				if (smsList == null) {
					smsList = new ArrayList<Sms>();
					smsMap.put(phone, smsList);
				}
				smsList.add(sms);

			} while (cur.moveToNext());
		}
		cur.close();
	}

	private void writeToSD() {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {

			return;
		}

		String pathName = "/sdcard/SmsToHtml/";

		File path = new File(pathName);

		if (!path.exists()) {
			path.mkdir();
		}
		path = null;
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String currentDateString = sf.format(System.currentTimeMillis());
		pathName = pathName + currentDateString + "/";
		path = new File(pathName);
		if (path.exists()) {
			return;
		} else {
			path.mkdir();
		}
		path = null;
		createIndexFile(pathName);
		createCss(pathName);
		createScript(pathName);
		createLeft(pathName);
		createAllContactMsg(pathName);
		/*
		 * String fileName = "index.html"; File file = new File(pathName +
		 * fileName); if (!file.exists()) { file.createNewFile();
		 * 
		 * }
		 * 
		 * BufferedWriter out = new BufferedWriter(new OutputStreamWriter( new
		 * FileOutputStream(file), "UTF-8"));
		 * 
		 * writeToStream(out);
		 * 
		 * out.close();
		 */

		Log.d("SmsToHtmlActivity", "finished");

	}

	private void createAllContactMsg(String path) {
		Iterator<String> it = smsMap.keySet().iterator();
		String phone = null;
		ArrayList<Sms> smsList = null;
		String name = null;
		BufferedWriter writer = null;
		File f = null;
		StringBuilder sb = new StringBuilder();
		try {
			while (it.hasNext()) {
				phone = it.next();
				smsList = smsMap.get(phone);
				name = getContactName(phone);
				f = new File(path + name + ".html");
				f.createNewFile();
				writer = getWriter(f);
				sb.delete(0, sb.length());
				sb.append(htmlHeader(name));
				sb.append("<link rel=\"stylesheet\" href=\"msg.css\" type=\"text/css\" />");
				sb.append("</head><body>");
				writer.write(sb.toString());
				for (Sms sms : smsList) {
					sb.delete(0, sb.length());
					sb.append("<h5>").append(name).append("</h5>");
					sb.append("<p>").append(sms.body).append("</p>");
					writer.write(sb.toString());
				}
				sb.delete(0, sb.length());
				sb.append("</body></html>");
				writer.write(sb.toString());
				writer.close();
				writer = null;
				f = null;
			}
		} catch (IOException e) {
			Log.e("ConvertThread", e.toString());
		}
	}

	private BufferedWriter getWriter(File f)
			throws UnsupportedEncodingException, FileNotFoundException {

		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(f), "UTF-8"));
		return out;
	}

	private boolean createLeft(String path) {
		boolean result = false;
		StringBuilder sb = new StringBuilder();
		sb.append(htmlHeader("联系人列表"));

		sb.append("<style type=\"text/css\">");
		sb.append("li{cursor:pointer;}</style>");
		sb.append("<script type=\"text/javascript\" src=\"script.js\"></script>");
		sb.append("</head>");
		sb.append("<body onload=\"onLoad()\">");
		sb.append("<ol>");

		Iterator<String> it = smsMap.keySet().iterator();
		String phone = null;
		String name = null;
		while (it.hasNext()) {
			phone = it.next();
			name = getContactName(phone);
			sb.append("<li>").append(name).append("</li>");
		}
		phone = null;
		name = null;
		sb.append("</ol></body></html>");

		result = writeToFile(path + "left.html", sb);
		sb = null;
		return result;
	}

	private boolean createIndexFile(String path) {
		StringBuilder sb = new StringBuilder();

		sb.append(htmlHeader("聊天记录"));

		sb.append("</head>");
		sb.append("<frameset cols=\"25%,70%\">");
		sb.append("<frame src=\"left.html\" />");
		Iterator<String> it = smsMap.keySet().iterator();
		if (it.hasNext()) {
			String phone = it.next();
			sb.append("<frame id=\"content\" src=\"").append(phone)
					.append(".html\"");
		} else {
			sb.append("<frame id=\"content\" src=\"\"");
		}
		it = null;

		sb.append("</frameset>");
		sb.append("</html>");
		boolean result = writeToFile(path + "index.html", sb);
		sb = null;
		return result;
	}

	private boolean createScript(String path) {
		StringBuilder sb = new StringBuilder();
		sb.append("function onLoad(){");
		sb.append("var e = document.getElementsByTagName('li');");
		sb.append("for(var i = 0; i < e.length; i++){");
		sb.append("e[i].onclick = function(){");
		sb.append("onSelected(this.innerHTML);");
		sb.append("};}}");
		sb.append("function onSelected(content){");
		sb.append("parent.frames[1].location = content+\".html\";}");
		boolean result = writeToFile(path + "script.js", sb);
		sb = null;
		return result;
	}

	private boolean createCss(String path) {
		StringBuilder sb = new StringBuilder();
		sb.append("p{background: rgb(245,245,245);");
		sb.append("border-style: dotted;");
		sb.append("border-color: rgb(119,136,085);");
		sb.append("border-width: 1px;");
		sb.append("margin-top: 0px;}");
		sb.append("h5{background: rgb(245,245,245);");
		sb.append("border-style: solid solid none solid;");
		sb.append("border-color: rgb(119,136,085);");
		sb.append("border-width: 1px;");
		sb.append("margin-bottom: 0px;");
		sb.append("text-align: left;");
		sb.append("display:inline;}");

		boolean result = writeToFile(path + "msg.css", sb);
		sb = null;

		return result;

	}

	public boolean writeToFile(String fileName, StringBuilder text) {

		BufferedWriter out = null;
		boolean result = false;
		try {

			File file = new File(fileName);
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(file), "UTF-8"));

			out.write(text.toString());

			result = true;
		} catch (IOException e) {
			result = false;
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		out = null;
		return result;

	}

	private void writeToStream(BufferedWriter writer) throws IOException {
		if (smsMap != null && smsMap.size() > 0) {
			Iterator<String> it = smsMap.keySet().iterator();
			String phone = null;
			ArrayList<Sms> smsList = null;
			String name = null;
			StringBuilder sb = new StringBuilder();
			sb.append(htmlHeader("TEST"));
			sb.append("<body>");
			writer.write(sb.toString());
			while (it.hasNext()) {
				phone = it.next();
				name = getContactName(phone);
				sb.delete(0, sb.length());
				smsList = smsMap.get(phone);

				for (Sms sms : smsList) {
					if (name != null) {
						sb.append("[").append(name).append("]<br>");
					} else {
						sb.append("[").append(phone).append("]<br>");
					}
					sb.append(sms.body).append("<br/>");
				}
				sb.append("----------------------------------------------------------------------<br/><br/>");

				writer.write(sb.toString());
				sb.delete(0, sb.length());
			}
			sb.append("</body></html>");
			writer.write(sb.toString());
			phone = null;
			smsList.clear();
			name = null;
			sb = null;
			smsMap.clear();
			it = null;

		}
	}

	private String htmlHeader(String title) {
		StringBuilder sb = new StringBuilder();
		sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
		sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
		sb.append("<head>");
		sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		sb.append("<meta http-equiv=\"content-language\" content=\"zh-CN\">");
		sb.append("<meta name=\"keywords\" content=\"SmsToHtml\">");
		sb.append("<meta name=\"description\" content=\"SmsToHtml\">");
		sb.append("<meta name=\"author\" content=\"HomeLink&lt;hliang@126.com&gt;\">");
		sb.append("<title>").append(title).append("</title>");

		return sb.toString();
	}

	private String getContactName(String phone) {

		String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME };
		Cursor cur = context.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				projection,
				ContactsContract.CommonDataKinds.Phone.NUMBER + " like '%"
						+ phone + "'", null, null);
		String name = null;
		if (cur.moveToFirst()) {
			name = cur
					.getString(cur
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
		}
		if (name == null) {
			name = phone;
		}
		cur.close();
		cur = null;
		projection = null;
		return name;

	}
}